package com.gj.demojuc.chap09;

/**
 * 编译器和处理器为了提高性能而进行指令重排序，多线程环境下有可能出现问题
 * 解决方案volatile关键字确保有序性
 */
public class VolatileOrderDemo {
    public volatile static int a,b;
    public static int x,y;
    public static void main(String[] args) throws InterruptedException {
        //主线程
        int i = 0;
        while (true){
            i++;
            a=b=x=y=0;
            //子线程
            Thread thread1 = new Thread(() -> {
                a=1;
                x=b;
            },"线程1");
            Thread thread2 = new Thread(() -> {
                b=1;
                y=a;
            }, "线程2");

            thread1.start();
            thread2.start();
            //等子线程执行完才执行主线程
            thread1.join();
            thread2.join();
            System.out.println("第" + i + "次打印：x=" + x + ", y=" + y);
            if (x==0 && y==0){
                break;
            }
        }
    }
}
